#!/bin/bash

source ./common.sh

# 提取JDK版本
jdk_version=$(basename ${jdk_package_path} .tar.gz | cut -d'-' -f2)
java_version="1.8.0_${jdk_version#*u}"

echo "提取JDK版本:jdk_version:${jdk_version} java_version:${java_version}"

# 提取JDK文件名
jdk_filename="jdk${java_version}"

echo "解压后的目录名为：${jdk_filename}"

# 定义环境变量
env_var_lines=(
  "#JAVA_HOME"
  "export JAVA_HOME=${module_path}/${jdk_filename}"
  "export PATH=\$PATH:\$JAVA_HOME/bin"
)

echo "准备进入for循环"

for server in "${servers[@]}"; do

  echo "进入for循环 ${server}"

  echo "开始安装JDK到 ${server}"

  # 同步JDK安装包
  
  echo "开始同步JDK安装包"
  
  if [ "${server}" != "${master_server}" ]; then
     sshpass -p "${new_user_password}" ssh -o StrictHostKeyChecking=no "${new_user}@${master_server}" "rsync -av ${jdk_package_path}  ${new_user}@${server}:${software_directory}"
  fi
  
  echo "同步JDK安装包完成"

  # 删除已存在的目录
  
  echo "开始删除已存在的目录"
  
  sshpass -p "${new_user_password}" ssh -o StrictHostKeyChecking=no "${new_user}@${server}" "sudo rm -rf /opt/module/jdk*"

  echo "删除已存在的目录完成"

  # 解压JDK到目标目录
  
  echo "开始解压JDK到目标目录"
  
  sshpass -p "${new_user_password}" ssh -o StrictHostKeyChecking=no "${new_user}@${server}" "tar -zxf ${jdk_package_path} -C ${module_path}"
  
  echo "解压JDK到目标目录完成"

  # 判断my_env.sh文件是否存在，如果不存在，新建
  
  echo "开始判断my_env.sh文件是否存在"
  
  sshpass -p "${new_user_password}" ssh -o StrictHostKeyChecking=no "${new_user}@${server}" "sudo touch /etc/profile.d/my_env.sh"

  echo "判断my_env.sh文件是否存在完成"

  # 删除原有的JAVA_HOME配置
  sshpass -p "${new_user_password}" ssh -o StrictHostKeyChecking=no "${new_user}@${server}" "sudo sed -i '/JAVA_HOME/d' /etc/profile.d/my_env.sh"

  # 追加新的JAVA_HOME配置
  for line in "${env_var_lines[@]}"; do
    sshpass -p "${new_user_password}" ssh -o StrictHostKeyChecking=no "${new_user}@${server}" "echo '${line}' | sudo tee -a /etc/profile.d/my_env.sh"
  done

  # 刷新环境变量
  sshpass -p "${new_user_password}" ssh -o StrictHostKeyChecking=no "${new_user}@${server}" "source /etc/profile"

  # 测试JDK是否安装成功
  java_installed_version=$(sshpass -p "${new_user_password}" ssh -o StrictHostKeyChecking=no "${new_user}@${server}" java -version 2>&1 | awk -F '\"' '/version/ {print $2}' | awk -F '\"' '{print $1}')
  
  echo "安装后的java_installed_version：${java_installed_version}"

  if [ "${java_installed_version}" == "${java_version}" ]; then
    echo "JDK安装成功：${server}"
  else
    echo "JDK安装失败：${server}"
  fi

  echo "注意：如果 'java -version' 可用，则无需重启。否则，请重启服务器。"
  echo "------------------------------------"
done
